<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-search" label="搜索" perms="sys:role:list" type="primary" @click="findPage(null)"/>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-plus" label="新增" perms="sys:role:add" type="success" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>
    <!--表格树内容栏-->
    <perm-table :page="page" :columns="columns" :selectionChange="selectionChange"
                :handleCurrentHandle="handleCurrentHandle" :loading="loading" size="mini"
                @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete"
                permsEdit="sys:role:update" permsDelete="sys:role:delete">
    </perm-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.roleId ? '新增用户' : '修改用户'" width="45%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
               label-width="80px" :size="size" style="text-align:left;">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="dataForm.roleName" placeholder="角色名称：如新闻管理员"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="dataForm.description" placeholder="角色描述：如新闻管理员可以新增编辑文章资讯内容等"></el-input>
        </el-form-item>
        <el-form-item label="角色授权" prop="permIds">
          <el-tree :data="permData" size="mini" show-checkbox node-key="permId" :props="defaultProps"
                   style="width: 100%;pading-top:20px;" ref="permTree" :render-content="renderContent"
                   v-loading="permLoading" element-loading-text="拼命加载中" :check-strictly="true"
                   @check-change="handlePermCheckChange">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">取消</el-button>
        <el-button :size="size"  type="primary" :loading="editLoading" @click="submitForm()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from '../../Component/PopupTreeInput/Index'
import PermButton from '../../Component/PermButton/Index'
import PermTable from '../../Component/PermTable/Index'
import TableColumnFilterDialog from '../../Component/TableColumnFilterDialog/Index'

export default {
    name: 'Role',
    components: {
        PermTable,
        PermButton,
        PopupTreeInput,
        TableColumnFilterDialog
    },
    data: function() {
        return {
            size: 'small',
            loading: false,
            editLoading: false,
            permLoading: false,
            filters: {
                roleName: ''
            },
            filterColumns: [],
            columns: [],
            page: {},
            pageRequest: {
                current: 1,
                size: 10
            },
            dialogVisible: false,
            dataForm: {
                roleId: 0,
                roleName: '',
                description: '',
                permIds: []
            },
            dataRule: {
                roleName: [{ required: true, message: '标题名称不能为空', trigger: 'blur' }],
                description: [{ required: true, message: '标题名称不能为空', trigger: 'blur' }]
            },
            permData: [],
            defaultProps: {
                children: 'children',
                label: 'description'
            }
        }
    },
    methods: {
    // 获取分页数据
        findPage: function(data) {
            this.loading = true
            if (data != null) {
                this.pageRequest = data.pageRequest
            }
            let param = {
                roleName: this.filters.roleName
            }
            param = Object.assign(param, this.pageRequest)
            this.$api.role.getRoleList(param).then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    this.loading = false
                    return
                }
                this.page = res.data
                this.loading = false
                this.findMenuData()
            }).then(data != null ? data.callback : '')
        },
        findMenuData: function() {
            if (this.permData && this.permData.length > 0) {
                return
            }
            this.$api.perm.getPermList().then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    return
                }
                this.permData = res.data
            })
        },
        // 显示新增界面
        handleAdd: function() {
            this.dialogVisible = true
            this.isEditPerm = true
            this.dataForm = {
                roleId: 0,
                roleName: '',
                description: '',
                permIds: []
            }
        },
        // 显示编辑界面
        handleEdit: function(data) {
            this.permLoading = true
            this.isEditPerm = false
            this.$api.role.getRolePermList({ roleId: data.row.roleId }).then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    return
                }
                this.dialogVisible = true
                Object.assign(this.dataForm, data.row)
                this.dataForm.permIds = res.data
                // 默认选中当前内容,挂载完成取$refs
                this.$nextTick(() => {
                    this.$refs.permTree.setCheckedKeys(res.data)
                    this.permLoading = false
                })
            })
        },
        // 删除
        handleDelete(data) {
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const params = this.getDeleteIds([], data.row)
                this.$api.role.deleteRole(params).then(res => {
                    if (!res.success) {
                        this.$message({ message: res.message, type: 'error' })
                        return
                    }
                    this.findTreeData()
                    this.$message({ message: '删除成功', type: 'success' })
                })
            })
        },
        // 获取删除的包含子分类的id列表
        getDeleteIds(ids, row) {
            ids.push(row.roleId)
            if (row.children != null) {
                for (let i = 0, len = row.children.length; i < len; i++) {
                    this.getDeleteIds(ids, row.children[i])
                }
            }
            return ids
        },
        selectionChange(selections) {
            console.log(selections)
        },
        handleCurrentHandle: function(val) {
            console.log(val)
        },
        // 表单提交
        submitForm() {
            var callback = (res) => {
                this.editLoading = false
                if (res.success) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    this.dialogVisible = false
                } else {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                }
                // 当前页
                this.findPage(null)
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true
                        const params = Object.assign({}, this.dataForm)
                        params.permIds = this.$refs.permTree.getCheckedKeys()
                        if (!this.dataForm.roleId) {
                            this.$api.role.saveRole(params).then(res => {
                                callback(res)
                            })
                        } else {
                            this.$api.role.updateRole(params).then(res => {
                                callback(res)
                            })
                        }
                    })
                }
            })
        },
        // 初始化表格
        initColums: function() {
            this.columns = [
                { prop: 'roleId', label: '角色ID', minWidth: 120 },
                { prop: 'roleName', label: '角色名称', minWidth: 250 },
                { prop: 'description', label: '角色描述', minWidth: 300 },
                { prop: 'updateTime', label: '更新时间', minWidth: 250 }
            ]
            this.filterColumns = JSON.parse(JSON.stringify(this.columns))
        },
        // 处理表格列过滤显示
        displayFilterColumnsDialog: function() {
            this.$refs.tableColumnFilterDialog.setDialogVisible(true)
        },
        // 处理表格列过滤显示
        handleFilterColumns: function(data) {
            this.filterColumns = data.filterColumns
            this.$refs.tableColumnFilterDialog.setDialogVisible(false)
        },
        // 树节点选择监听
        handlePermCheckChange(data, check, subCheck) {
            if (check) {
                // 节点选中时同步选中父节点
                const parentId = data.parentId
                this.$refs.permTree.setChecked(parentId, true, false)
            } else {
                // 节点取消选中时同步取消选中子节点
                if (data.children != null) {
                    data.children.forEach(element => {
                        this.$refs.permTree.setChecked(element.id, false, false)
                    })
                }
            }
        },
        renderContent(h, { node, data, store }) {
            return (
                <div class="column-container">
                    <span style="text-algin:center;margin-right:80px;">{data.description}</span>
                    <span style="text-algin:center;margin-right:80px;">
                        <el-tag type={data.permType === '目录' ? '' : data.permType === '菜单' ? 'success' : 'warning'} size="small">
                            {data.permType}
                        </el-tag>
                    </span>
                    <span style="text-algin:center;margin-right:80px;"> <i class={data.icon}></i></span>
                    <span style="text-algin:center;margin-right:80px;">{data.parentName ? data.parentName : '顶级菜单'}</span>
                    <span style="text-algin:center;margin-right:80px;">{data.permUrl ? data.permUrl : '\t'}</span>
                </div>)
        }
    },
    mounted() {
        this.initColums()
        this.findPage(null)
    }
}
</script>

<style scoped>
</style>
